const mongoose = require('mongoose');
const db = "mongodb://localhost/simle-db";
const glob = require('glob');
const {resolve} = require('path');

mongoose.Promise = global.Promise;

exports.connect = ()=>{
    mongoose.connect(db);

    return new Promise((resolve,reject)=>{
        let maxConnectTimes = 0;
        var mydb = mongoose.connection;
        mydb.on('disconnected', () => {
            console.log("********数据库链接断开了！********");
            if(maxConnectTimes<3){
                maxConnectTimes++;
                mongoose.connect(db);
            }else{
                reject();
                throw new Error("数据库出现问题，程序无法搞定，请人工处理")
            }
           
        });

        mydb.on('error',err=>{
            console.log("********数据库链接错误！********");
            if(maxConnectTimes<3){
                maxConnectTimes++;
                mongoose.connect(db);
            }else{
                reject(err);
                throw new Error("数据库出现问题，程序无法搞定，请人工处理")
            }
        });

        mydb.once('open',()=>{
            console.log('MongoDB Connectd Successfully!')
            resolve();
        })


    })
   
   

   

   
};

exports.initSchemas = ()=>{
    glob.sync(resolve(__dirname,'./schema/**/*.js')).forEach(require)
}